class Solution {
public:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    bool check[10][10];
    bool exist(vector<vector<char>>& board, string word) {
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[0].size(); ++j) {
                if (board[i][j] == word[0]) {
                    check[i][j] = true;
                    if (dfs(board, i, j, word, 1))
                        return true;
                    check[i][j] = false;
                }
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>>& board, int i, int j, string word, int pos) {
        if (pos >= word.size()) {
            return true;
        }

        for (int k = 0; k < 4; ++k) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if (x >= 0 && y >= 0 && x < board.size() && y < board[0].size() &&
                check[x][y] == false && board[x][y] == word[pos]) {
                check[x][y] = true;
                if (dfs(board, x, y, word, pos + 1))
                    return true;
                check[x][y] = false;
            }
        }
        return false;
    }
};
